<?php
/**
 *
 * 调休 Action
 * author：悟空HR
**/
class LieuAction extends Action{

	public function _initialize(){
		$action = array(
			'users'=>array('index','add', 'edit', 'delete', 'view',),
			'anonymous'=>array()
		);
		B('Authenticate', $action);
	}

	public function index(){
		$search_user_name = empty($_GET['search_user_name']) ? '' : trim($_GET['search_user_name']);
		$search_category = empty($_GET['search_category']) ? '' : intval($_GET['search_category']);
		$search_status = '' == $_GET['search_status'] ? '' : intval($_GET['search_status']);
		$search_start_time = empty($_GET['search_start_time']) ? '' : strtotime($_GET['search_start_time']);
		$search_end_time = empty($_GET['search_end_time']) ? '' : strtotime($_GET['search_end_time']);

		if(!empty($search_user_name)){
			$condition['user_name'] = $search_user_name;
		}
		if(!empty($search_category)){
			$condition['lieu_category_id'] = $search_category;
		}
		if('' !== $search_status){
			$condition['status'] = $search_status;
		}
		if(!empty($search_start_time)){
			if(!empty($search_end_time)){
				$condition['start_time'] = array('between', array($search_start_time, $search_end_time));
			}else{
				$condition['start_time'] = array('between', array($search_start_time-1, $search_start_time+86400));
			}
		}
		if(!empty($search_end_time)){
			if(!empty($search_start_time)){
				$condition['end_time'] = array('between', array($search_start_time, $search_end_time));
			}else{
				$condition['end_time'] = array('between', array($search_end_time-1, $search_end_time+86400));
			}
		}
	
		$p = $this->_get('p','intval',1);
		$lieulist = D('Lieu')->getLieu($p, $condition);
		$this->lieulist = $lieulist['lieulist'];
		$this->assign('page', $lieulist['page']);
		$this->alert = parseAlert();
		$this->display();
	}
	
	public function add(){
		if ($this->isPost()) {
			$data['user_id'] = trim($_POST['user_id']);
			$data['maker_user_id'] = session('user_id');
			$data['lieu_category_id'] = $_POST['lieu_category_id'];
			$data['start_time'] = strtotime($_POST['start_time']);
			$data['end_time'] = strtotime($_POST['end_time']);
			$data['content'] = $_POST['content'];
			$data['create_time'] = time();
			$data['status'] = 0;
			
			if('' == $data['user_id']){
				alert('error','未选择调休的员工！',$_SERVER['HTTP_REFERER']);
			}
			if('' == $data['start_time']){
					alert('error','请设置开始时间！',$_SERVER['HTTP_REFERER']);
			}
			if('' == $data['end_time']){
				alert('error','请设置结束时间！',$_SERVER['HTTP_REFERER']);
			}
			if('' == $data['content']){
				alert('error','未填写调休原因！',$_SERVER['HTTP_REFERER']);
			}
			
			$d_lieu = D('Lieu');
			$d_user = D('User');
			$user = $d_user->getUserInfo(['user_id' => $data['user_id']]);
			// 减去加班时间
			$new_lieu_time = $data['end_time'] - $data['start_time'];
			if($user['available_overtime'] < $new_lieu_time){
				alert('error','可用加班时间('. sprintf('%.2f', $user['available_overtime']/3600) .'小时)不够！',$_SERVER['HTTP_REFERER']);
			}
			// $user['overtime'] = $user['overtime'] - $new_lieu_time;
			// // 添加调休时间。
			// $user['lieutime'] = $user['lieutime'] + $new_lieu_time; 

			if($d_lieu->addLieu($data) /*&& $d_user->editUserInfo($user)*/){
				// 只有在审核过后才会修改用户数据。
				alert('success','添加成功！', U('hrm/lieu/index'));
			}else{
				alert('error','添加失败！', U('hrm/lieu/index'));
			}
		}else{
			$this->maker_user_name = session('name');
			$this->alert = parseAlert();
			$this->display();
		}
	}
	
	public function view(){
		$lieu_id = $_GET['id'];
		if(!empty($lieu_id)){
			$d_lieu = D('Lieu');
			$lieu = $d_lieu->getLieuById($lieu_id);
			$this->lieu = $lieu;
		}else{
			alert('error', '参数错误！', U('hrm/lieu/index'));
		}
		$this->alert = parseAlert();
		$this->display();
	}
	
	
	public function edit(){
		$lieu_id = $_REQUEST['id'];
		if(!empty($lieu_id)){
			$d_lieu = D('Lieu');
			if ($this->isPost()) {
				$data['lieu_id'] = $lieu_id;
				$data['user_id'] = trim($_POST['user_id']);
				$data['maker_user_id'] = session('user_id');
				$data['lieu_category_id'] = $_POST['lieu_category_id'];
				$data['start_time'] = strtotime($_POST['start_time']);
				$data['end_time'] = strtotime($_POST['end_time']);
				$data['content'] = $_POST['content'];
				
				if('' == $data['user_id']){
					alert('error','未选择调休的员工！',$_SERVER['HTTP_REFERER']);
				}
				if ($_POST['user_id'] !== session('user_id') && !session('?admin')) {
					alert('error','只能修改自己的记录！',$_SERVER['HTTP_REFERER']);
				}
				if('' == $data['start_time']){
						alert('error','请设置开始时间！',$_SERVER['HTTP_REFERER']);
				}
				if('' == $data['end_time']){
					alert('error','请设置结束时间！',$_SERVER['HTTP_REFERER']);
				}
				if('' == $data['content']){
					alert('error','未填写调休原因！',$_SERVER['HTTP_REFERER']);
				}

				// 修改调休时间
				$back_lieu = $d_lieu->getLieuById($lieu_id);
				if($back_lieu['status'] == 1 && !session('?admin')){
					alert('error','已经审核通过的加班记录不能编辑（请联系管理员）！',$_SERVER['HTTP_REFERER']);
				}
				
				// 减去加班时间
				$new_lieu_time = $data['end_time'] - $data['start_time'];
				$old_lieu_time = $back_lieu['end_time'] - $back_lieu['start_time'];
				// $user['overtime'] = $user['overtime'] - $old_lieu_time;
				$available_overtime = $user['available_overtime'] + $old_lieu_time; // 总的可用加班时间
				if($available_overtime < $new_lieu_time){
					alert('error','加班时间('. sprintf('%.2f', $available_overtime/3600) .'小时)不够！',$_SERVER['HTTP_REFERER']);
				}
				
				// 减去老的调休时间
				// $user['lieutime'] = $user['lieutime'] - $old_lieu_time;
				// 添加新的调休时间。 
				// $user['lieutime'] = $user['lieutime'] + $new_lieu_time; 
				// $diff_lieu_time = $new_lieu_time - $old_lieu_time;

				// $user['overtime'] = $user['overtime'] + $old_lieu_time - $new_lieu_time;

				if($d_lieu->editLieu($data)){
					alert('success','编辑成功！', U('hrm/lieu/view', 'id='.$lieu_id));
				}else{
					alert('error','编辑失败！', U('hrm/lieu/view', 'id='.$lieu_id));
				}
			}else{
				$this->lieu = $d_lieu->getLieuById($lieu_id);
			}
		}else{
			alert('error', '参数错误！', U('hrm/lieu/index'));
		}
		$this->alert = parseAlert();
		$this->display();
	}
	
	//删除加班记录
	public function delete(){
		$lieu_id = $_REQUEST['id'];
		if (!empty($lieu_id)){
			$d_lieu = D('Lieu');
			$back_lieu = $d_lieu->getLieuById($lieu_id);
			if ($back_lieu['user_id'] !== session('user_id') && !session('?admin')) {
				alert('error','只能删除自己的记录！',$_SERVER['HTTP_REFERER']);
			}
			if ($back_lieu['status'] == 1 && !session('?admin')) {
				alert('error','已经审核通过的调休记录不能删除（请联系管理员）！',$_SERVER['HTTP_REFERER']);
			}
			
			// 把调休时间加到加班时间中去。
			// $user['overtime'] = $user['overtime'] + $old_lieu_time;
			// 减去对应的调休时间
			// $user['lieutime'] = $user['lieutime'] - $old_lieu_time; 
			$result = true;
			if ($back_lieu['status'] == 1) {
				# 审核通过的调休删除，必须更新用户数据。
				$old_lieu_time = $back_lieu['end_time'] - $back_lieu['start_time'];
				$old_lieu_time = 0 - $old_lieu_time;
				$result = $result && $this->modifySingleUserOvertimeAndLieutime($back_lieu['user_id'], $old_lieu_time);
			}
			if ( $result && $d_lieu->deleteLieu($lieu_id)) {
				alert('success', '删除成功！', U('hrm/lieu/index'));
			}else{
				alert('error', '删除失败！', U('hrm/lieu/index'));
			}
		} else {
			alert('error', '删除失败，未选择需要删除的记录！', U('hrm/lieu/index'));
		}
	}
	
	// 审核
	// `status` int(1) NOT NULL COMMENT '0:审核中  1:通过 2:未通过'
	public function auditing(){
		$lieu_id = $_REQUEST['id'];
		$data['lieu_id'] = $lieu_id ;
		$data['status'] = $_REQUEST['status'];
		if (empty($data['lieu_id'])){
			alert('error', '未选择需要审核的记录！', U('hrm/lieu/index'));
		}
		if ('' == $data['status']){
			alert('error', '未选择审核状态！', U('hrm/lieu/index'));
		}
		if (!session('?admin')){
			alert('error', '只有管理员才能审核！', U('hrm/lieu/index'));
		}
		$d_lieu = D('Lieu');
		$lieu = $d_lieu->getLieuById($lieu_id);
		if($data['status'] == $lieu['status']){
			alert('error', '请勿重复审核', U('hrm/lieu/index'));
		}else{				
			$result = true;
			// add by chensy 增加加班时间记录。
			if (is_array($data['lieu_id'])) {
				foreach ($data['lieu_id'] as $lieu_id) {
					$result = $result && $this->doModifyUserOvertimeAndLieutime($lieu_id, $data['status']);
				}
			}else {
				$result = $result && $this->doModifyUserOvertimeAndLieutime($data['lieu_id'], $data['status']);
			}
			if ($result && $d_lieu->auditingLieu($data)) {
				alert('success', '审核成功('.$overtime['status'].'->'.$data['status'].')！', U('hrm/lieu/index'));
			}else{
				alert('error', '审核失败！', U('hrm/lieu/index'));
			}
		}
	}

	private function doModifyUserOvertimeAndLieutime($lieu_id, $dst_status){
		$d_lieu = D('Lieu');
		$lieu = $d_lieu->getLieuById($lieu_id);
		$diff_lieutime = $lieu['end_time'] - $lieu['start_time'];
		if (($lieu['status'] == 0 && $dst_status == 1)
				|| ($lieu['status'] == 2 && $dst_status == 1)) {
			# 之前是处理中,审核通过
			if($this->modifySingleUserOvertimeAndLieutime(
					$lieu['user_id'], 
					$diff_lieutime)){
				// 修改成功，不做提示，继续修改。
			}else {
				# 提示修改失败，不跑后续的操作。
				// alert('error', '审核失败('.$lieu['user_id'].'1->2)！', U('hrm/lieu/index'));
				return false;
			}
		}elseif ($lieu['status'] == 1 && $dst_status == 2) {
			# 之前是审核通过,现在是审核不通过
			if($this->modifySingleUserOvertimeAndLieutime(
					$lieu['user_id'], 
					0 - $diff_lieutime)){
				// 修改成功，不做提示，继续修改。
			}else {
				# 提示修改失败，不跑后续的操作。
				// alert('error', '审核失败('.$lieu['user_id'].'1->2)！', U('hrm/lieu/index'));
				return false;
			}
		}
		return true;
	}

   /**
	* 修改single用户的加班数据。
	*/
	private function modifySingleUserOvertimeAndLieutime($user_id, $new_lieutime_value){
		$d_user = D('User');
		$user = $d_user->getUserInfo(['user_id' => $user_id]);
		$user['lieutime'] = $user['lieutime'] + $new_lieutime_value;
		return $d_user->editUserInfo($user);
	}
}